package net.pingfang.devicelock.Decoder;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.pingfang.devicelock.WebSocketHandler;
import net.pingfang.devicelock.constant.PacketDecoder;
import net.pingfang.devicelock.dto.Code0200;
import net.pingfang.devicelock.util.DeviceDecodeUtil;
import org.springframework.web.socket.WebSocketSession;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class Type0200Decoder implements PacketDecoder<Code0200> {

    private final WebSocketHandler customWebSocketHandler;

    public Type0200Decoder(ConcurrentHashMap<String, WebSocketSession> sessions){
        this.customWebSocketHandler = new WebSocketHandler(sessions);
    }
    @Override
    public Code0200 decode(byte[] packet) {
        ObjectMapper objectMapper = new ObjectMapper();
        Code0200 entity = null;
        try {
            objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
            // JSON → 实体类（自动映射嵌套结构）new String(packet, StandardCharsets.UTF_8))
            entity = objectMapper.readValue(DeviceDecodeUtil.TrimDecode(
                    packet) , Code0200.class);
            log.info("entity{}", entity);
            //发送信息到前端vue
            String json = new ObjectMapper().writeValueAsString(entity);
            customWebSocketHandler.sendToAll(json);
        } catch (JsonProcessingException e) {
            log.error("AsyncHandler类异常==》{}",e.getMessage());
        }
        return entity;
    }


}
